﻿<%@ WebHandler Language="C#" Class="customerManager" %>

using System;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using Chenxin.Lib.Utility;

public class customerManager : AjaxHandlerBase
{

    public customerManager()
    {
        //添加客需
        htTypePermit.Add("add", Constants.Permit_CustomerAdd);
        //编辑客需
        htTypePermit.Add("edit", Constants.Permit_CustomerEdit);
        //记录无效
        htTypePermit.Add("updstatus", Constants.Permit_CustomerUnable);
        //设置类别
        htTypePermit.Add("updcatalog", Constants.Permit_CustomerSetType);
        //设定公开级别
        htTypePermit.Add("setpublevel", Constants.Permit_SetCustomerPubLevel);
    }
    override public void RequestProcess(HttpContext context)
    {
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "getlist":
                strResponse = GetList(context);
                break;
            case "getcustomerinfo":
                strResponse = GetCustomerDemand(context);
                break;
            case "getcustomertracelist":
                strResponse = GeCustomerTraceList(context);
                break;
            case "add":
                strResponse = addCustomerInfo(context);
                break;
            case "edit":
                strResponse = editCustomerInfo(context);
                break;
            case "updstatus":
                strResponse = updCustomerStatus(context);
                break;
            case "updcatalog":
                strResponse = updCustomerCatalog(context);
                break;
            case "chkover":
                strResponse = chkOverOfPrivCustomerCnt(context);
                break;
            case "setpublevel":
                strResponse = setDemandPubLevel(context);
                break; 
            case "getdemand"://获取需求列表
                strResponse = getDemandByCustomerId(context);
                break;
            default:
                break;
        }

        context.Response.ContentType = "text/plain";
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        context.Response.Write(strResponse);
    }
    
    private string GetList(HttpContext context) {
      
        try {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数

            string fieldlist = "DemandId,OprPerson,OprDepart,CustomerName,DemandKind,DemandType,DemandZone ,TotalPrice,HouseUse ,Consider,DemandArea,ServiceDemand,HouseBuyTime,DemandBuilding,SpecialDemand,DemandStyle_Room,DemandStyle_Hall,DemandStyle_Toilet,UnitPrice,Fitment,ReturnRate,Catalog,Addtime,LastTraceDay,Status,DateInterval,PubLevel";
            string fieldtablelist = "DemandId,OprPerson,OprDepart,CustomerName,case DemandKind when '10' then '求购' else '求租' end as DemandKind,case DemandType when '10' then '住房' when '20' then '商铺' else '办公' end as DemandType ,DemandZone ,TotalPrice,HouseUse ,Consider,DemandArea,ServiceDemand,HouseBuyTime,DemandBuilding,SpecialDemand,DemandStyle_Room,DemandStyle_Hall,DemandStyle_Toilet,UnitPrice,Fitment,ReturnRate,Catalog,Convert(varchar(10),Addtime,120) as Addtime,LastTraceDay,Status,(SELECT (CASE WHEN OverTimeTraceNum=0 THEN -100 ELSE (DATEDIFF(DAY,LastTraceDay,GETDATE())- OverTimeTraceNum) END) FROM House_BusinessSetting WHERE DepartId = OprDepartId) As DateInterval,";
            fieldtablelist = fieldtablelist + "(Case When PubLevel=0 Then '私客' When PubLevel=10 Then '公司级共享' When PubLevel=20 Then '跨部级共享' When PubLevel=30 Then '本部级共享' Else '' End) As PubLevel";
         
            string orderfield = "Customer_DemandInfo.Addtime desc";

            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid areaid = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departid = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userid = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);
            
            //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (userid != Guid.Empty)
                sb.AppendFormat(" AND (OprPersonId = '{0}') ", userid);
            else if (departid != Guid.Empty)
                sb.AppendFormat(" AND (OprDepartId = '{0}')", departid);
            else if (areaid != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaid);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaid);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                sb.AppendFormat(" AND (OprDepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (company != Guid.Empty)
                sb.AppendFormat(" AND (OprDepartId in (Select DepartId from v_Hr_DepartmentInfo where CompanyId = '{0}'))", company);
            else if (city != Guid.Empty)
                sb.AppendFormat(" AND (OprDepartId in (Select DepartId from v_Hr_DepartmentInfo where CityId = '{0}'))", city);
            else
                sb.AppendFormat(" AND (OprDepartId in (Select DepartId from v_Hr_DepartmentInfo where CompanyId = '{0}'))", CurrentUserInfo.CompanyId);

            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();

            //私客户权限SQL
            System.Text.StringBuilder strSqlPriv = new System.Text.StringBuilder();
            //公客户权限SQL
            System.Text.StringBuilder strSqlPub = new System.Text.StringBuilder();

            //所有私客户权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllPrivDemand))
            {
                strSqlPriv.Append(" (PubLevel = 0) ");
            }
            //本城市所有私客户权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityPrivDemand))
            {
                strSqlPriv.AppendFormat(" (PubLevel = 0 And CityId='{0}') ", CurrentUserInfo.CityId);
            }
            //本公司所有私客户权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyPrivDemand))
            {
                strSqlPriv.AppendFormat(" (PubLevel =0 And CompanyId='{0}') ", CurrentUserInfo.CompanyId);
            }
            //本部门私客户权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartPrivDemand))
            {
                strSqlPriv.Append(" EXISTS(");
                strSqlPriv.Append("Select 1 From v_Struct_UserDepartRelation M ");
                strSqlPriv.AppendFormat("WHERE Customer_DemandInfo.OprDepartId = M.Departid AND  M.Userid= '{0}' ", CurrentUserInfo.UserId);
                strSqlPriv.Append("AND Customer_DemandInfo.PubLevel = 0 AND M.ViewPrivDemand =1) ");
            }

            //所有公客户权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllPubDemand))
            {
                strSqlPub.Append(" (PubLevel > 0) ");
            }
            //本城市所有公客户权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityPubDemand))
            {
                strSqlPub.AppendFormat(" (PubLevel > 0 And CityId='{0}') ", CurrentUserInfo.CityId);
            }
            //本公司所有公司共享池的公客户权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyPubShareDemand))
            {
                strSqlPub.AppendFormat(" (PubLevel = 10 And CompanyId='{0}') ", CurrentUserInfo.CompanyId);
            }
            //跨部门共享池的公客户权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCrossDepartPubShareDemand))
            {
                strSqlPub.Append(" (EXISTS(");
                strSqlPub.Append("Select 1 From v_Struct_UserDepartRelation M ");
                strSqlPub.AppendFormat("WHERE Customer_DemandInfo.OprDepartId = M.Departid And M.Userid= '{0}' ", CurrentUserInfo.UserId);
                strSqlPub.Append("And ((Customer_DemandInfo.PubLevel = 20 AND M.ViewCrossPubShareDemand =1) ");
                strSqlPub.Append("Or (Customer_DemandInfo.PubLevel = 30 AND M.ViewPubShareDemand =1))) ");
                strSqlPub.AppendFormat(" Or (PubLevel = 10 And CompanyId='{0}') Or (PubLevel > 0 And OprDepartId='{1}')) ", CurrentUserInfo.CompanyId, CurrentUserInfo.DepartId);
            }
            //本部门共享池的公客户权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartPubShareDemand))
            {
                strSqlPub.AppendFormat(" ((PubLevel = 10 And CompanyId='{0}') OR (PubLevel > 0 And OprDepartId='{1}')) ", CurrentUserInfo.CompanyId, CurrentUserInfo.DepartId);
            }

            if (strSqlPub.Length > 0 && strSqlPriv.Length > 0)
            {
                sb1.AppendFormat(" ({0} Or {1}) ", strSqlPub, strSqlPriv);
            }
            else if (strSqlPub.Length + strSqlPriv.Length > 0)
            {
                //sb1.Append(strSqlPriv.ToString());
                //sb1.Append(strSqlPub.ToString());
                sb1.AppendFormat(" ({0} Or {1} )", strSqlPriv.ToString() + strSqlPub.ToString(), string.Format("OprPersonId='{0}'", CurrentUserInfo.UserId));
            }
            else
            {
                sb1.AppendFormat(" (OprPersonId='{0}') ", CurrentUserInfo.UserId);
            }
            
            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            string stime = context.Request.QueryString["stime"];
            string etime = context.Request.QueryString["etime"];
            string demandkind = context.Request.QueryString["demandkind"];
            string demandtype = context.Request.QueryString["demandtype"];
            string status = context.Request.QueryString["status"];
            string demandzone = context.Request.QueryString["demandzone"];
            string demandbuilding = context.Request.QueryString["demandbuilding"];
            string demandarea = context.Request.QueryString["demandarea"];
            string totalprice = context.Request.QueryString["totalprice"];
            string unitprice = context.Request.QueryString["unitprice"];
            string catalog = context.Request.QueryString["catalog"];
            string publevel = context.Request.QueryString["PubLevel"];
            string usercode = context.Request.QueryString["usercode"];
                        
            if (!String.IsNullOrEmpty(stime))
            {
                sb1.Append(string.Format(" AND DATEDIFF(DD,Addtime,'{0}') <= 0", stime));
            }
            if (!String.IsNullOrEmpty(etime))
            {
                sb1.Append(string.Format(" AND DATEDIFF(DD,Addtime,'{0}') >= 0", etime));
            }
            if (!String.IsNullOrEmpty(demandkind))
            {
                sb1.Append(string.Format("AND demandkind = '{0}'",demandkind));
            }
            if (!String.IsNullOrEmpty(demandtype))
            {
                sb1.Append(string.Format("AND DemandType = '{0}'", demandtype));
            }
            if (!String.IsNullOrEmpty(status))
            {
                sb1.Append(string.Format(" and Status= '{0}'", status));
            }
            if (!String.IsNullOrEmpty(demandzone))
            {
                sb1.Append(string.Format(" and DemandZone like '%{0}%'", demandzone));
            }
            if (!String.IsNullOrEmpty(demandbuilding))
            {
                sb1.Append(string.Format(" and demandbuilding like '%{0}%'", demandbuilding));
            }
            if (!String.IsNullOrEmpty(demandarea))
            {
                sb1.Append(string.Format(" and demandarea like '%{0}%'", demandarea));
            }
            if (!String.IsNullOrEmpty(totalprice))
            {
                sb1.Append(string.Format(" and totalprice like '%{0}%'", totalprice));
            }
            if (!String.IsNullOrEmpty(unitprice))
            {
                sb1.Append(string.Format(" and unitprice like '%{0}%'", unitprice));
            }
            if (!String.IsNullOrEmpty(catalog))
            {
                sb1.AppendFormat(" and catalog = '{0}'", catalog);
            }
            if (!String.IsNullOrEmpty(publevel))
            {
                sb1.AppendFormat(" and publevel = {0}", publevel);
            }
            if (!string.IsNullOrEmpty(usercode))
            {
                sb1.AppendFormat(" and OprPersonId=(select UserId from v_Hr_User_BaseInfo where UserCode='{0}') ", usercode);
            }
            
            //描述：快速搜索参数拼接
            //添加人：薛彦
            //添加日期：2010-04-26
            if (context.Request["quicktype"] != null)
            {
                switch (context.Request["quicktype"])
                {
                    case "owner"://我的客源
                        sb1.AppendFormat(" And(AddPersonId='{0}')", CurrentUserInfo.UserId);
                        break;
                    case "depart"://本店客源
                        sb1.AppendFormat(" And(AddDepartId='{0}')", CurrentUserInfo.DepartId);
                        break;
                    case "today"://本日客源
                        sb1.AppendFormat(" And (datediff(d,Addtime,'{0}')=0)", DateTime.Now);
                        break;
                    case "thismonth"://本月客源
                        sb1.AppendFormat(" And (datediff(m,Addtime,'{0}')=0)", DateTime.Now);
                        break;
                    case "favor":// 我的收藏 
                        sb1.AppendFormat(" And (CustomerId in (select FavorId from Personal_FavorsInfo where FavorPersonId = '{0}' and FavorType = 1 ))", CurrentUserInfo.UserId);
                        break;
                }
            }
            
            //判断权限范围结束////////////////////////////////////////////
            
            System.Data.DataSet dskeylist = null;
            dskeylist = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetList(
                iPageIndex, iPageSize, orderfield, "Customer_DemandInfo", sb1.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)dskeylist.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetKeyListHtml(dskeylist, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml);
            }
            dskeylist.Dispose();
            dskeylist = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
         }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }

    /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private bool GetKeyListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            string strClass = String.Empty;
            string strFontColor = string.Empty;
            
            sb.Append("<table style=\"width:2300px\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\" >");
            sb.Append("<thead><tr>");
            sb.Append("<th width=\"100px\">门店</th>");
            sb.Append("<th width=\"80px\">业务员</th>");
            sb.Append("<th width=\"80px\">客户姓名</th>");
            sb.Append("<th width=\"90px\">公开级别</th>");
            sb.Append("<th width=\"70px\">需求种类</th>");
            sb.Append("<th width=\"70px\">需求类型</th>");
            sb.Append("<th width=\"120px\">需求区域</th>");
            sb.Append("<th width=\"100px\">需求面积</th>");
            sb.Append("<th width=\"100px\">总(售/租)价</th>");
            sb.Append("<th width=\"40px\">类别</th>");
            sb.Append("<th width=\"120px\">需求时间</th>");
            sb.Append("<th width=\"150px\">房屋用途</th>");
            sb.Append("<th width=\"150px\">考虑因素</th>");
            sb.Append("<th width=\"150px\">服务需求</th>");
            sb.Append("<th width=\"120px\">物业类型</th>");
            sb.Append("<th width=\"120px\">特殊需求</th>");
            sb.Append("<th width=\"70px\">房型需求</th>");
            sb.Append("<th width=\"120px\">单价</th>");
            sb.Append("<th width=\"120px\">装修情况</th>");
            sb.Append("<th width=\"120px\">期望回报率</th>");
            sb.Append("<th width=\"80px\">建档时间</th>");
            sb.Append("<th width=\"120px\">跟单时间</th>");
            sb.Append("</tr></thead><tbody>");
            
            foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
            {
                //样式
                strClass = "tr_houselist ";
                //字体颜色
                strFontColor = string.Empty;
                //最后期限之前两天
                if (Convert.ToInt32(Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DateInterval", "0")) + 2 >= 0 &&
                    Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "PubLevel", "").Equals("私客"))
                {
                    strFontColor = "style=\"color:red\"";
                }
                if (Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Status", "") == "-1")
                {
                    strClass = strClass + " clsInvalid ";
                }
                else
                {
                    if (Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Catalog", "") != "")
                    {
                        strClass = strClass + "clsCatalog" + Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Catalog", "");
                    }
                }
                sb.AppendFormat("<tr id=\"{0}\" class=\"{1}\" style=\"white-space:nowrap;\">", row["DemandId"].ToString(),strClass);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprDepart", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprPerson", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CustomerName", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "PubLevel", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DemandKind", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DemandType", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DemandZone", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DemandArea", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TotalPrice", "0") + "万", strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Catalog", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseBuyTime", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseUse", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Consider", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ServiceDemand", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DemandBuilding", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "SpecialDemand", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DemandStyle_Room", "") + "/" + Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DemandStyle_Hall", "") + "/" + Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DemandStyle_Toilet", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "UnitPrice", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Fitment", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ReturnRate", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Addtime", ""), strFontColor);
                sb.AppendFormat("<td {1}>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "LastTraceDay", ""), strFontColor);
                sb.Append("</tr>");
            }

            sb.Append("</tbody></table>");
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }
    
    /// <summary>
    /// 获取展开层中需要房源数据。数据以实体转换成Json返回。
    /// </summary>
    /// <param name="context"></param>
    private string GetCustomerDemand(HttpContext context)
    {
        try
        {
            //Guid demandid = (string.IsNullOrEmpty(context.Request["demandid"])) ?  : new Guid(context.Request["demandid"]);
            //if (demandid == Guid.Empty)
            //{
            //    return string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，客需标识丢失");
            //}
            string demandid = context.Request.Params["demandid"];
            if(string.IsNullOrEmpty(demandid))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，客需标识丢失");
            }

            //需求信息
            Chenxin.Lib.House.Entity.Customer_DemandInfo entDemandInfo = Chenxin.Lib.House.BLL.Custom_Info.GetCustomerDemandInfoById(demandid);
            //客户信息
            Chenxin.Lib.House.Entity.Customer_BaseInfo entBaseInfo = Chenxin.Lib.House.BLL.Custom_Info.GetCustomBaseInfo(entDemandInfo.CustomerId.ToString());
            
            if (entDemandInfo == null || entBaseInfo == null)
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，找不到对应的客源");
            }
            return string.Format("{{success:'1',msg:'成功',data:{{demandinfo:{0},baseinfo:{1}}}}}",
                                  Chenxin.Lib.Utility.JsonHelp.Convert2Json(entDemandInfo),
                                  Chenxin.Lib.Utility.JsonHelp.Convert2Json(entBaseInfo));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }

    }
    /// <summary>
    /// 根据参数中的房源ID查询房源跟单数据;
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private string GeCustomerTraceList(HttpContext context)
    {
        try
        {
            Guid houseId = (string.IsNullOrEmpty(context.Request["customerid"])) ? Guid.Empty : new Guid(context.Request["customerid"]);
            if (houseId == Guid.Empty)
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，房源标识丢失");
            }

            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "*";
            string fieldtablelist = "*";
            string orderfield = "House_TraceInfo.TraceTime desc";
            string strwhere = string.Format("(houseId='{0}' AND IsHide = 0 AND Status = 1)", houseId);

            System.Data.DataSet dshousetracelist = null;
            if (iPageIndex == 1)
            {
                //分页第一页从缓存中读取
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
                string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE, houseId);

                dshousetracelist = cs.GetDataSet(strCachKey);
                if (!cs.Hit)
                {
                    //若未命中。从查询数据库中读取
                    dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                        iPageIndex, iPageSize, orderfield, "House_TraceInfo", strwhere, fieldlist, fieldtablelist, true);

                    cs.Set(strCachKey, dshousetracelist, DateTime.Now.AddMinutes(5));
                }
            }
            else
            {
                dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                iPageIndex, iPageSize, orderfield, "House_TraceInfo", strwhere, fieldlist, fieldtablelist, true);
            }

            int count = (int)dshousetracelist.Tables[1].Rows[0][0];

            string strHtml = "";
            if (!GetHouseTraceListHtml(dshousetracelist, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
            }

            dshousetracelist.Dispose();
            dshousetracelist = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);

        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }
    /// <summary>
    /// 生成房源跟单列表
    /// </summary>
    /// <param name="dslist"></param>
    /// <param name="strHtml"></param>
    /// <returns></returns>
    private bool GetHouseTraceListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
     
        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            sb.AppendFormat("<div class=\"infos\" style=\"width: 640px;\" title=\"{0}\"> <span class=\"rb\" style=\"width:380px\">{0}</span><span class=\"rbpsn\" style=\"width:120px\">{1}</span><span class=\"rbtim\" style=\"width:120px\">{2:yyyy-MM-dd HH:mm}</span> </div>",
                DatasetHelper.GetValue(row, "TraceContext", ""),
                DatasetHelper.GetValue(row, "Tractor", "-") + "/" + DatasetHelper.GetValue(row, "Depart", "-"),
                DatasetHelper.GetValue(row, "TraceTime", ""));
        }

        strHtml = sb.ToString();
        return true;
    }

    //*******************************************
    //功能概要       ：添加用户信息
    //参数説明       ：context 请求的上下文
    //返回值説明     ：回传数据
    //功能詳細       ：添加用户信息
    //作成者         ：he.jifeng 
    //作成日         ：2010-04-23
    //*******************************************
    private string addCustomerInfo(HttpContext context)
    {
        string strRet;
        try
        {
            string clientModel = context.Request.Params["model"];
            //客户基本信息
            string strBaseInfo = Regex.Replace(clientModel, @"DemandInfo_([\s\S])*?\042([\s\S])*?\042,", "", RegexOptions.None);
            strBaseInfo = Regex.Replace(strBaseInfo, @"DemandInfo_([\s\S])*?\042([\s\S])*?\042\}", "}", RegexOptions.None);
            strBaseInfo = strBaseInfo.Replace(",}", "}").Replace("CustomerInfo_", "");
            //客户需求信息
            string strDemandInfo = Regex.Replace(clientModel, @"CustomerInfo_([\s\S])*?\042([\s\S])*?\042,", "", RegexOptions.None);
            strDemandInfo = Regex.Replace(strDemandInfo, @"CustomerInfo_([\s\S])*?\042([\s\S])*?\042\}", "}", RegexOptions.None);
            strDemandInfo = strDemandInfo.Replace(",}", "}").Replace("DemandInfo_", "");

            //客源基本信息实体对象
            Chenxin.Lib.House.Entity.Customer_BaseInfo entBaseInfo =
            (Chenxin.Lib.House.Entity.Customer_BaseInfo)JsonHelp.Convert2Entity(strBaseInfo, typeof(Chenxin.Lib.House.Entity.Customer_BaseInfo));

            //客源需求信息实体对象
            Chenxin.Lib.House.Entity.Customer_DemandInfo entDemandInfo =
            (Chenxin.Lib.House.Entity.Customer_DemandInfo)JsonHelp.Convert2Entity(strDemandInfo, typeof(Chenxin.Lib.House.Entity.Customer_DemandInfo));

            //添加客户信息
            entBaseInfo = completeBaseInfo(entBaseInfo, entDemandInfo);
            //添加客户需求信息
            entDemandInfo = completeDemandInfo(entBaseInfo, entDemandInfo);

            //添加客源信息
            string CustomerCode = Chenxin.Lib.House.BLL.Custom_Info.AddCustomInfo(entBaseInfo, entDemandInfo);

            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "添加了一个客源:客户姓名[" + entBaseInfo.CustomerName + "]",
                    OperationType.OperationTypeComboList()["OprType_CustomerAdd"].ToString());

            strRet = retExecResult(Constants.ExecResult.Succ, "添加成功", CustomerCode);
            return strRet;
        }
        catch (Exception ex)
        {
            strRet = retExecResult(Constants.ExecResult.Error, ex.Message, "");
            return strRet;
        }
    }

    //检查私客户数量
    private string chkOverOfPrivCustomerCnt(HttpContext context)
    {
        int CntOfPriv = 0;
        string strRet = string.Empty;
        
        //需求客户数量上限
        int iLimitCntOfCustomer = Chenxin.Lib.House.BLL.Custom_Info.getCntOfCustomerLimit(CurrentUserInfo.DepartId);
        if (iLimitCntOfCustomer > 0)
        {
            Chenxin.Lib.House.BLL.Customer_BaseInfo bllBaseInfo = new Chenxin.Lib.House.BLL.Customer_BaseInfo();
            //当前用户所有需求客户数量
            int iCntOfCustomer = bllBaseInfo.GetCntOfCustomer(CurrentUserInfo.UserId);
            //超过上限
            if (iCntOfCustomer >= iLimitCntOfCustomer)
            {
                CntOfPriv = iCntOfCustomer;
            }
        }

        strRet = retExecResult(Constants.ExecResult.Succ, "", CntOfPriv);
        return strRet;
    }
    
    //补充客户基本信息
    private Chenxin.Lib.House.Entity.Customer_BaseInfo completeBaseInfo(Chenxin.Lib.House.Entity.Customer_BaseInfo entBaseInfo, Chenxin.Lib.House.Entity.Customer_DemandInfo entDemandInfo)
    {
        //设置客源基本信息
        entBaseInfo.OprPersonId = CurrentUserInfo.UserId;      //操作经纪人Id      GUID
        entBaseInfo.OprPerson = CurrentUserInfo.UserName;               //操作经纪        
        entBaseInfo.OprDepartId = CurrentUserInfo.DepartId;   //操作经纪人部门Id  GUID
        entBaseInfo.OprDepart = CurrentUserInfo.DepartName;               //操作经纪人部门
        entBaseInfo.LastTraceDay = DateTime.Now; //最后跟进日期
        entBaseInfo.CompanyId = CurrentUserInfo.CompanyId;
        entBaseInfo.CompanyName = CurrentUserInfo.CompanyName;
        entBaseInfo.CityId = CurrentUserInfo.CityId;
        entBaseInfo.CityName = CurrentUserInfo.CityName;

        entBaseInfo.CustomerId = Guid.NewGuid();
        entBaseInfo.Adddate = DateTime.Now;             //建档日期
        entBaseInfo.AddPersonId = CurrentUserInfo.UserId;      //所属经纪人Id      GUID
        entBaseInfo.AddPerson = CurrentUserInfo.UserName;               //所属经纪人
        entBaseInfo.AddDepartId = CurrentUserInfo.DepartId;   //属经纪人部门Id    GUID
        entBaseInfo.AddDepart = CurrentUserInfo.DepartName;               //所属经纪人部门
        entBaseInfo.LastTraceDay = DateTime.Now; //最后跟进日期
        entBaseInfo.CustomerKind = 20;
        entBaseInfo.Status = 1;
        //entBaseInfo.IsPub = false;

        entBaseInfo.PubLevel = entDemandInfo.PubLevel;
        return entBaseInfo;
    }

    private Chenxin.Lib.House.Entity.Customer_DemandInfo completeDemandInfo(Chenxin.Lib.House.Entity.Customer_BaseInfo entBaseInfo, Chenxin.Lib.House.Entity.Customer_DemandInfo entDemandInfo)
    {
        entDemandInfo.DemandId = Guid.NewGuid();
        entDemandInfo.CustomerId = entBaseInfo.CustomerId;
        entDemandInfo.CustomerName = entBaseInfo.CustomerName;
        entDemandInfo.ServiceNum = 0;
        entDemandInfo.Status = 1;
        entDemandInfo.Addtime = DateTime.Now;
        entDemandInfo.Updatetime = DateTime.Now;
        entDemandInfo.AddPersonId = CurrentUserInfo.UserId;
        entDemandInfo.AddPerson = CurrentUserInfo.UserName;
        entDemandInfo.AddDepartId = CurrentUserInfo.DepartId;
        entDemandInfo.AddDepart = CurrentUserInfo.DepartName;
        entDemandInfo.OprPersonId = CurrentUserInfo.UserId;
        entDemandInfo.OprPerson = CurrentUserInfo.UserName;
        entDemandInfo.OprDepartId = CurrentUserInfo.DepartId;
        entDemandInfo.OprDepart = CurrentUserInfo.DepartName;
        entDemandInfo.CompanyId = CurrentUserInfo.CompanyId;
        entDemandInfo.CompanyName = CurrentUserInfo.CompanyName;
        entDemandInfo.CityId = CurrentUserInfo.CityId;
        entDemandInfo.CityName = CurrentUserInfo.CityName;
        entDemandInfo.LastTraceDay = DateTime.Now;

        //设置房源配对条件
        entDemandInfo.Filter = getFilter(entDemandInfo);

        return entDemandInfo;
    }

    //*******************************************
    //功能概要       ：生成房源配对条件
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：生成房源配对条件
    //作成者         ：姚志强
    //作成日         ：2010-03-23
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string getFilter(Chenxin.Lib.House.Entity.Customer_DemandInfo customerDemandInfo)
    {
        StringBuilder filter = new StringBuilder();
        filter.Append(" 1 = 1");

        if (!string.IsNullOrEmpty(customerDemandInfo.DemandZone))
        {
            filter.Append(" AND(");
            string[] zoneArray = Regex.Split(customerDemandInfo.DemandZone, ",");

            filter.Append(" Region = '").Append(zoneArray[0]).Append("'");
            for (int i = 1; i < zoneArray.Length; i++)
            {
                filter.Append(" OR Region = '").Append(zoneArray[i]).Append("'");
            }

            filter.Append(")");
        }

        if (!string.IsNullOrEmpty(customerDemandInfo.TotalPrice))
        {
            filter.Append(" AND (");
            string[] tPriceArray = Regex.Split(customerDemandInfo.TotalPrice, ",");
            bool tPriceFlag = false;

            for (int i = 0; i < tPriceArray.Length; i++)
            {
                if (tPriceArray[i].IndexOf("<") > -1 || tPriceArray[i].IndexOf(">") > -1)
                {
                    if (tPriceFlag)
                    {
                        filter.Append(" OR SalePrice_T ").Append(tPriceArray[i].Substring(0, 1)).Append(Convert.ToInt16(tPriceArray[i].Substring(1)) * 10000);
                    }
                    else
                    {
                        filter.Append(" SalePrice_T ").Append(tPriceArray[i].Substring(0, 1)).Append(Convert.ToInt16(tPriceArray[i].Substring(1)) * 10000);
                        tPriceFlag = true;
                    }
                }

                if (tPriceArray[i].IndexOf("-") > -1)
                {
                    if (tPriceFlag)
                    {
                        filter.Append(" OR (SalePrice_T >= ").Append(Convert.ToInt16(Regex.Split(tPriceArray[i], "-")[0]) * 10000);
                        filter.Append(" AND SalePrice_T <= ").Append(Convert.ToInt16(Regex.Split(tPriceArray[i], "-")[1]) * 10000).Append(")");

                    }
                    else
                    {
                        filter.Append(" (SalePrice_T >= ").Append(Convert.ToInt16(Regex.Split(tPriceArray[i], "-")[0]) * 10000);
                        filter.Append(" AND SalePrice_T <= ").Append(Convert.ToInt16(Regex.Split(tPriceArray[i], "-")[1]) * 10000).Append(")");
                        tPriceFlag = true;
                    }
                }
            }
            filter.Append(")");
        }

        if (!string.IsNullOrEmpty(customerDemandInfo.DemandArea))
        {
            filter.Append(" AND (");
            string[] areaArray = Regex.Split(customerDemandInfo.DemandArea, ",");
            bool areaFlag = false;

            for (int i = 0; i < areaArray.Length; i++)
            {
                if (areaArray[i].IndexOf("<") > -1 || areaArray[i].IndexOf(">") > -1)
                {
                    if (areaFlag)
                    {
                        filter.Append(" OR BuildingArea ").Append(areaArray[i]);
                    }
                    else
                    {
                        filter.Append(" BuildingArea ").Append(areaArray[i]);
                        areaFlag = true;
                    }
                }

                if (areaArray[i].IndexOf("-") > -1)
                {
                    if (areaFlag)
                    {
                        filter.Append(" OR (BuildingArea >= ").Append(Regex.Split(areaArray[i], "-")[0]);
                        filter.Append(" AND BuildingArea <= ").Append(Regex.Split(areaArray[i], "-")[1]).Append(")");

                    }
                    else
                    {
                        filter.Append(" (BuildingArea >= ").Append(Regex.Split(areaArray[i], "-")[0]);
                        filter.Append(" AND BuildingArea <= ").Append(Regex.Split(areaArray[i], "-")[1]).Append(")");
                        areaFlag = true;
                    }
                }
            }
            filter.Append(")");
        }

        if (!string.IsNullOrEmpty(customerDemandInfo.DemandBuilding))
        {
            filter.Append(" AND(");
            string[] typeArray = Regex.Split(customerDemandInfo.DemandBuilding, ",");

            filter.Append(" BuildingType = '").Append(typeArray[0]).Append("'");
            for (int i = 1; i < typeArray.Length; i++)
            {
                filter.Append(" OR BuildingType = '").Append(typeArray[i]).Append("'");
            }
            filter.Append(")");
        }

        if (!string.IsNullOrEmpty(customerDemandInfo.UnitPrice))
        {
            filter.Append(" AND (");
            string[] uPriceArray = Regex.Split(customerDemandInfo.UnitPrice, ",");
            bool uPriceFlag = false;
            string filedName = "";

            if (10 == customerDemandInfo.DemandKind)
                filedName = "SalePrice_U";
            else
                filedName = "RentPrice";

            for (int i = 0; i < uPriceArray.Length; i++)
            {
                if (uPriceArray[i].IndexOf("<") > -1 || uPriceArray[i].IndexOf(">") > -1)
                {
                    if (uPriceFlag)
                    {
                        filter.Append(" OR ").Append(filedName).Append(uPriceArray[i]);
                    }
                    else
                    {
                        filter.Append(" ").Append(filedName).Append(uPriceArray[i]);
                        uPriceFlag = true;
                    }
                }

                if (uPriceArray[i].IndexOf("-") > -1)
                {
                    if (uPriceFlag)
                    {
                        filter.Append(" OR (").Append(filedName).Append(" >= ").Append(Regex.Split(uPriceArray[i], "-")[0]);
                        filter.Append(" AND ").Append(filedName).Append(" <= ").Append(Regex.Split(uPriceArray[i], "-")[1]).Append(")");

                    }
                    else
                    {
                        filter.Append(" (").Append(filedName).Append(" >= ").Append(Regex.Split(uPriceArray[i], "-")[0]);
                        filter.Append(" AND ").Append(filedName).Append(" <= ").Append(Regex.Split(uPriceArray[i], "-")[1]).Append(")");
                        uPriceFlag = true;
                    }
                }
            }
            filter.Append(")");
        }

        return filter.ToString();
    }

    //编辑客户信息
    private string editCustomerInfo(HttpContext context)
    {
        string strRet = string.Empty;
        try
        {
            string clientModel = context.Request.Params["model"];
            string type = context.Request.Params["type"];

            if (type == "BaseInfo")
            {
                strRet = updateBaseInfo(clientModel);
            }
            else if (type == "DemandInfo")
            {
                strRet = updateDemandInfo(clientModel);
            }
            
            //strRet = retExecResult(Constants.ExecResult.Succ, "更新成功", "");
            return strRet;
        }
        catch (Exception ex)
        {
            strRet = retExecResult(Constants.ExecResult.Error, ex.Message, "");
            return strRet;
        }
    }

    //更新基本信息
    private string updateBaseInfo(string clientModel)
    {
        string strRet = string.Empty;
        
        //客户基本信息
        string strBaseInfo = Regex.Replace(clientModel, @"DemandInfo_([\s\S])*?\042([\s\S])*?\042,", "", RegexOptions.None);
        strBaseInfo = Regex.Replace(strBaseInfo, @"DemandInfo_([\s\S])*?\042([\s\S])*?\042\}", "}", RegexOptions.None);
        strBaseInfo = strBaseInfo.Replace(",}", "}").Replace("CustomerInfo_", "");

        //客源基本信息实体对象
        Chenxin.Lib.House.Entity.Customer_BaseInfo entUpdBaseInfo =
        (Chenxin.Lib.House.Entity.Customer_BaseInfo)JsonHelp.Convert2Entity(strBaseInfo, typeof(Chenxin.Lib.House.Entity.Customer_BaseInfo));

        Chenxin.Lib.House.Entity.Customer_BaseInfo entBaseInfo = Chenxin.Lib.House.BLL.Custom_Info.GetCustomBaseInfo(entUpdBaseInfo.CustomerId.ToString());

        //数据变更
        if (entBaseInfo == null)
        {
            strRet = retExecResult(Constants.ExecResult.Error, "数据已变更，请刷新后重新执行操作", "");
        }
        else
        {
            //设置客源基本信息
            entBaseInfo.LastTraceDay = DateTime.Now;                                       //最后跟进日期

            entBaseInfo.CustomerName = entUpdBaseInfo.CustomerName;                        //客户姓名
            entBaseInfo.Address = entUpdBaseInfo.Address;                                  //联系地址
            entBaseInfo.Mobile = entUpdBaseInfo.Mobile;                                    //手机
            entBaseInfo.Phone = entUpdBaseInfo.Phone;                                      //电话
            entBaseInfo.Nationality = entUpdBaseInfo.Nationality;                          //国籍
            entBaseInfo.Sex = entUpdBaseInfo.Sex;                                          //性别
            entBaseInfo.CertificateType = entUpdBaseInfo.CertificateType;                  //证件类型
            entBaseInfo.CertificateNo = entUpdBaseInfo.CertificateNo;                      //证件号码
            entBaseInfo.CustomerType = entUpdBaseInfo.CustomerType;                        //客户类型
            entBaseInfo.CustomerKind = entUpdBaseInfo.CustomerKind;
            entBaseInfo.Status = entUpdBaseInfo.Status;
            //entBaseInfo.IsPub = entUpdBaseInfo.IsPub;
            entBaseInfo.PubLevel = entUpdBaseInfo.PubLevel;
            entBaseInfo.LastTraceDay = DateTime.Now;

            Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
            house_TraceInfo.TractorId = CurrentUserInfo.UserId;
            house_TraceInfo.Tractor = CurrentUserInfo.UserName;
            house_TraceInfo.Depart = CurrentUserInfo.DepartName;
            house_TraceInfo.DepartId = CurrentUserInfo.DepartId;
            house_TraceInfo.CityId = CurrentUserInfo.CityId;
            house_TraceInfo.CityName = CurrentUserInfo.CityName;
            house_TraceInfo.CompanyId = CurrentUserInfo.CompanyId;
            house_TraceInfo.CompanyName = CurrentUserInfo.CompanyName;

            //添加客源信息
            string strTemp = Chenxin.Lib.House.BLL.Custom_Info.UpdateCustomBaseInfo(entBaseInfo, house_TraceInfo);
            strRet = retExecResult(Constants.ExecResult.Succ, "更新成功", "");
        }

        return strRet;
    }

    //更新需求信息
    private string updateDemandInfo(string clientModel)
    {
        string strRet = string.Empty;
        //客户需求信息
        string strDemandInfo = Regex.Replace(clientModel, @"CustomerInfo_([\s\S])*?\042([\s\S])*?\042,", "", RegexOptions.None);
        strDemandInfo = Regex.Replace(strDemandInfo, @"CustomerInfo_([\s\S])*?\042([\s\S])*?\042\}", "}", RegexOptions.None);
        strDemandInfo = strDemandInfo.Replace(",}", "}").Replace("DemandInfo_", "");

        //客源需求信息实体对象
        Chenxin.Lib.House.Entity.Customer_DemandInfo entDemandInfo =
        (Chenxin.Lib.House.Entity.Customer_DemandInfo)JsonHelp.Convert2Entity(strDemandInfo, typeof(Chenxin.Lib.House.Entity.Customer_DemandInfo));

        Chenxin.Lib.House.Entity.Customer_DemandInfo entOldDemandInfo = Chenxin.Lib.House.BLL.Custom_Info.GetCustomerDemandInfoById(entDemandInfo.DemandId.ToString());

        if (entOldDemandInfo == null)
        {
            strRet = retExecResult(Constants.ExecResult.Error, "数据已变更，请刷新后重新执行操作", "");
        }
        else
        {
            entDemandInfo.CustomerId = entOldDemandInfo.CustomerId;
            entDemandInfo.CustomerCode = entOldDemandInfo.CustomerCode;
            entDemandInfo.CustomerName = entOldDemandInfo.CustomerName;
            entDemandInfo.CompanyId = entOldDemandInfo.CompanyId;
            entDemandInfo.CompanyName = entOldDemandInfo.CompanyName;
            entDemandInfo.CityId = entOldDemandInfo.CityId;
            entDemandInfo.CityName = entOldDemandInfo.CityName;
            entDemandInfo.Catalog = entOldDemandInfo.Catalog;
            entDemandInfo.Status = entOldDemandInfo.Status;
            entDemandInfo.Addtime = entOldDemandInfo.Addtime;
            entDemandInfo.Updatetime = DateTime.Now;
            entDemandInfo.AddPersonId = entDemandInfo.AddPersonId;
            entDemandInfo.AddPerson = entOldDemandInfo.AddPerson;
            entDemandInfo.AddDepartId = entOldDemandInfo.AddDepartId;
            entDemandInfo.AddDepart = entOldDemandInfo.AddDepart;
            entDemandInfo.OprPersonId = entOldDemandInfo.OprPersonId;
            entDemandInfo.OprPerson = entOldDemandInfo.OprPerson;
            entDemandInfo.OprDepartId = entOldDemandInfo.OprDepartId;
            entDemandInfo.OprDepart = entOldDemandInfo.OprDepart;
            entDemandInfo.LastTraceDay = DateTime.Now;
            
            ////求购住宅
            //if (entDemandInfo.DemandKind == 10 && entDemandInfo.DemandType == 10)
            //{ 
            //    //购房时间
            //    entOldDemandInfo.HouseBuyTime = entDemandInfo.HouseBuyTime;
            //    //欲购区域
            //    entOldDemandInfo.DemandZone = entDemandInfo.DemandZone;
            //    //物业类型
            //    entOldDemandInfo.DemandBuilding = entDemandInfo.DemandBuilding;
            //    //欲购面积(㎡)
            //    entOldDemandInfo.DemandArea = entDemandInfo.DemandArea;
            //    //欲购单价 (元/㎡)
            //    entOldDemandInfo.UnitPrice = entDemandInfo.UnitPrice;
            //    //欲购总价(万元)
            //    entOldDemandInfo.TotalPrice = entDemandInfo.TotalPrice;
            //    //购房目的
            //    entOldDemandInfo.HouseUse = entDemandInfo.HouseUse;
            //    //考虑因素
            //    entOldDemandInfo.Consider = entDemandInfo.Consider;
            //    //服务需求
            //    entOldDemandInfo.ServiceDemand = entDemandInfo.ServiceDemand;
            //    //装修情况
            //    entOldDemandInfo.Fitment = entDemandInfo.Fitment;
            //    //房间类型需求： 	
            //    entOldDemandInfo.DemandStyle_Room = entDemandInfo.DemandStyle_Room;
            //    //厅房类型需求： 
            //    entOldDemandInfo.DemandStyle_Hall = entDemandInfo.DemandStyle_Hall;
            //    //卫生间类型需求： 	
            //    entOldDemandInfo.DemandStyle_Toilet = entDemandInfo.DemandStyle_Toilet;
            //    //特殊要求
            //    entOldDemandInfo.SpecialDemand = entDemandInfo.SpecialDemand;
            //    //备注
            //    entOldDemandInfo.Remark = entDemandInfo.Remark;
            //}
            //else if (entDemandInfo.DemandKind == 10 && entDemandInfo.DemandType == 20) {
            //    //购房时间
            //    entOldDemandInfo.HouseBuyTime = entDemandInfo.HouseBuyTime;
            //    //欲购区域
            //    entOldDemandInfo.DemandZone = entDemandInfo.DemandZone;
            //    //物业类型
            //    entOldDemandInfo.DemandBuilding = entDemandInfo.DemandBuilding;
            //    //欲购面积(㎡)
            //    entOldDemandInfo.DemandArea = entDemandInfo.DemandArea;
            //    //欲购单价 (元/㎡)
            //    entOldDemandInfo.UnitPrice = entDemandInfo.UnitPrice;
            //    //欲购总价(万元)
            //    entOldDemandInfo.TotalPrice = entDemandInfo.TotalPrice;
            //    //购房目的
            //    entOldDemandInfo.HouseUse = entDemandInfo.HouseUse;
            //    //考虑因素
            //    entOldDemandInfo.Consider = entDemandInfo.Consider;
            //    //期望回报率
            //    entOldDemandInfo.ReturnRate = entDemandInfo.ReturnRate;
            //    //备注
            //    entOldDemandInfo.Remark = entDemandInfo.Remark;
            //}  else if (entDemandInfo.DemandKind == 10 && entDemandInfo.DemandType == 30)
            //{
            //    //购房时间
            //    entOldDemandInfo.HouseBuyTime = entDemandInfo.HouseBuyTime;
            //    //欲购区域
            //    entOldDemandInfo.DemandZone = entDemandInfo.DemandZone;
            //    //物业类型
            //    entOldDemandInfo.DemandBuilding = entDemandInfo.DemandBuilding;
            //    //欲购面积(㎡)
            //    entOldDemandInfo.DemandArea = entDemandInfo.DemandArea;
            //    //欲购单价 (元/㎡)
            //    entOldDemandInfo.UnitPrice = entDemandInfo.UnitPrice;
            //    //欲购总价(万元)
            //    entOldDemandInfo.TotalPrice = entDemandInfo.TotalPrice;
            //    //考虑因素
            //    entOldDemandInfo.Consider = entDemandInfo.Consider;
            //    //期望回报率
            //    entOldDemandInfo.ReturnRate = entDemandInfo.ReturnRate;
            //    //备注
            //    entOldDemandInfo.Remark = entDemandInfo.Remark;
            //}
            //else if (entDemandInfo.DemandKind == 20 && entDemandInfo.DemandType == 10)
            //{
            //    //购房时间
            //    entOldDemandInfo.HouseBuyTime = entDemandInfo.HouseBuyTime;
            //    //欲购区域
            //    entOldDemandInfo.DemandZone = entDemandInfo.DemandZone;
            //    //物业类型
            //    entOldDemandInfo.DemandBuilding = entDemandInfo.DemandBuilding;
            //    //欲购面积(㎡)
            //    entOldDemandInfo.DemandArea = entDemandInfo.DemandArea;
            //    //欲购单价 (元/㎡)
            //    entOldDemandInfo.UnitPrice = entDemandInfo.UnitPrice;
            //    //购房目的
            //    entOldDemandInfo.HouseUse = entDemandInfo.HouseUse;
            //    //装修情况
            //    entOldDemandInfo.Fitment = entDemandInfo.Fitment;
            //    //房间类型需求： 	
            //    entOldDemandInfo.DemandStyle_Room = entDemandInfo.DemandStyle_Room;
            //    //厅房类型需求： 
            //    entOldDemandInfo.DemandStyle_Hall = entDemandInfo.DemandStyle_Hall;
            //    //卫生间类型需求： 	
            //    entOldDemandInfo.DemandStyle_Toilet = entDemandInfo.DemandStyle_Toilet;
            //    //特殊要求
            //    entOldDemandInfo.SpecialDemand = entDemandInfo.SpecialDemand;
            //    //备注
            //    entOldDemandInfo.Remark = entDemandInfo.Remark;
            //}
            //else if (entDemandInfo.DemandKind == 20 && entDemandInfo.DemandType == 20)
            //{
            //    //购房时间
            //    entOldDemandInfo.HouseBuyTime = entDemandInfo.HouseBuyTime;
            //    //欲购区域
            //    entOldDemandInfo.DemandZone = entDemandInfo.DemandZone;
            //    //物业类型
            //    entOldDemandInfo.DemandBuilding = entDemandInfo.DemandBuilding;
            //    //欲购面积(㎡)
            //    entOldDemandInfo.DemandArea = entDemandInfo.DemandArea;
            //    //欲购单价 (元/㎡)
            //    entOldDemandInfo.UnitPrice = entDemandInfo.UnitPrice;
            //    //购房目的
            //    entOldDemandInfo.HouseUse = entDemandInfo.HouseUse;
            //    //考虑因素
            //    entOldDemandInfo.Consider = entDemandInfo.Consider;
            //    //期望回报率
            //    entOldDemandInfo.ReturnRate = entDemandInfo.ReturnRate;
            //    //备注
            //    entOldDemandInfo.Remark = entDemandInfo.Remark;
            //}
            //else if (entDemandInfo.DemandKind == 20 && entDemandInfo.DemandType == 30)
            //{
            //    //购房时间
            //    entOldDemandInfo.HouseBuyTime = entDemandInfo.HouseBuyTime;
            //    //欲购区域
            //    entOldDemandInfo.DemandZone = entDemandInfo.DemandZone;
            //    //物业类型
            //    entOldDemandInfo.DemandBuilding = entDemandInfo.DemandBuilding;
            //    //欲购面积(㎡)
            //    entOldDemandInfo.DemandArea = entDemandInfo.DemandArea;
            //    //欲购单价 (元/㎡)
            //    entOldDemandInfo.UnitPrice = entDemandInfo.UnitPrice;
            //    //考虑因素
            //    entOldDemandInfo.Consider = entDemandInfo.Consider;
            //    //期望回报率
            //    entOldDemandInfo.ReturnRate = entDemandInfo.ReturnRate;
            //    //备注
            //    entOldDemandInfo.Remark = entDemandInfo.Remark;
            //}
            
            //entOldDemandInfo.DemandKind = entDemandInfo.DemandKind;
            //entOldDemandInfo.DemandType = entDemandInfo.DemandType;
            //entOldDemandInfo.Updatetime = DateTime.Now;
            //entOldDemandInfo.LastTraceDay = DateTime.Now;

            //设置房源配对条件
            entDemandInfo.Filter = getFilter(entDemandInfo);

            Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
            house_TraceInfo.TractorId = CurrentUserInfo.UserId;
            house_TraceInfo.Tractor = CurrentUserInfo.UserName;
            house_TraceInfo.Depart = CurrentUserInfo.DepartName;
            house_TraceInfo.DepartId = CurrentUserInfo.DepartId;
            house_TraceInfo.CityId = CurrentUserInfo.CityId;
            house_TraceInfo.CityName = CurrentUserInfo.CityName;
            house_TraceInfo.CompanyId = CurrentUserInfo.CompanyId;
            house_TraceInfo.CompanyName = CurrentUserInfo.CompanyName;
            //添加客源信息
            string strTemp = Chenxin.Lib.House.BLL.Custom_Info.UpdateCustomDemandInfo(entDemandInfo, house_TraceInfo);

            strRet = retExecResult(Constants.ExecResult.Succ, "更新成功", "");
        }
        return strRet;
    }

    //更新记录状态
    private string updCustomerStatus(HttpContext context)
    {
        string strRet = string.Empty;
        try
        {
            string demandId = context.Request.QueryString["demandid"];
            string status = context.Request.QueryString["status"];

            Chenxin.Lib.House.Entity.Customer_DemandInfo customerDemandInfo = Chenxin.Lib.House.BLL.Custom_Info.GetCustomerDemandInfoById(demandId);

            if (customerDemandInfo == null)
            {
                strRet = retExecResult(Constants.ExecResult.Error, "数据已变更，请刷新后重新执行操作", "");
            }
            else
            {
                if (!string.IsNullOrEmpty(status))
                {
                    customerDemandInfo.Status = Convert.ToInt32(status);
                }

                //customerDemandInfo.OprPersonId = CurrentUserInfo.UserId;
                //customerDemandInfo.OprPerson = CurrentUserInfo.UserName;
                //customerDemandInfo.OprDepartId = CurrentUserInfo.DepartId;
                //customerDemandInfo.OprDepart = CurrentUserInfo.DepartName;
                customerDemandInfo.Updatetime = DateTime.Now;

                //string strTemp = Chenxin.Lib.House.BLL.Custom_Info.UpdateCustomerDemand(customerDemandInfo);

                Chenxin.Lib.House.Entity.House_TraceInfo entTraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
                entTraceInfo.TractorId = CurrentUserInfo.UserId;
                entTraceInfo.Tractor = CurrentUserInfo.UserName;
                entTraceInfo.Depart = CurrentUserInfo.DepartName;
                entTraceInfo.DepartId = CurrentUserInfo.DepartId;
                entTraceInfo.CityId = CurrentUserInfo.CityId;
                entTraceInfo.CityName = CurrentUserInfo.CityName;
                entTraceInfo.CompanyId = CurrentUserInfo.CompanyId;
                entTraceInfo.CompanyName = CurrentUserInfo.CompanyName;
                //添加客源信息
                string strTemp = Chenxin.Lib.House.BLL.Custom_Info.UpdateCustomDemandInfo(customerDemandInfo, entTraceInfo);

                //添加用户操作日志 2010-5-11 王玮 Add
                string strStatus = string.Empty;
                if (status == "-1")
                    strStatus = "记录无效";
                else if (status == "1")
                    strStatus = "记录有效";

                //AddLog("" + CurrentUserInfo.UserName + "更改了一个客源记录状态:客户姓名[" + customerDemandInfo.CustomerName + "]已更改记录状态为:[" + strStatus + "]",
                //        OperationType.OperationTypeComboList()["OprType_SetCustomerStatus"].ToString());

                strRet = retExecResult(Constants.ExecResult.Succ, "状态变更成功", "");
            }
            
            return strRet;
        }
        catch (Exception ex)
        {
            strRet = retExecResult(Constants.ExecResult.Error, ex.Message, "");
            return strRet;
        }
    }

    //类别设置
    private string updCustomerCatalog(HttpContext context)
    {
        string strRet = string.Empty;
        try
        {
            Chenxin.Lib.House.Entity.Customer_DemandInfo entCustDemandInfo =
            (Chenxin.Lib.House.Entity.Customer_DemandInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Customer_DemandInfo));

            Chenxin.Lib.House.Entity.Customer_DemandInfo customerDemandInfo = Chenxin.Lib.House.BLL.Custom_Info.GetCustomerDemandInfoById(entCustDemandInfo.DemandId.ToString());

            if (customerDemandInfo == null)
            {
                strRet = retExecResult(Constants.ExecResult.Error, "数据已变更，请刷新后重新执行操作", "");
            }
            else
            {
                customerDemandInfo.Catalog = entCustDemandInfo.Catalog;

                //customerDemandInfo.OprPersonId = CurrentUserInfo.UserId;
                //customerDemandInfo.OprPerson = CurrentUserInfo.UserName;
                //customerDemandInfo.OprDepartId = CurrentUserInfo.DepartId;
                //customerDemandInfo.OprDepart = CurrentUserInfo.DepartName;
                customerDemandInfo.Updatetime = DateTime.Now;

                //string strTemp = Chenxin.Lib.House.BLL.Custom_Info.UpdateCustomerDemand(customerDemandInfo);

                Chenxin.Lib.House.Entity.House_TraceInfo entTraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
                entTraceInfo.TractorId = CurrentUserInfo.UserId;
                entTraceInfo.Tractor = CurrentUserInfo.UserName;
                entTraceInfo.Depart = CurrentUserInfo.DepartName;
                entTraceInfo.DepartId = CurrentUserInfo.DepartId;
                entTraceInfo.CityId = CurrentUserInfo.CityId;
                entTraceInfo.CityName = CurrentUserInfo.CityName;
                entTraceInfo.CompanyId = CurrentUserInfo.CompanyId;
                entTraceInfo.CompanyName = CurrentUserInfo.CompanyName;
                //添加客源信息
                string strTemp = Chenxin.Lib.House.BLL.Custom_Info.UpdateCustomDemandInfo(customerDemandInfo, entTraceInfo);

                ////添加用户操作日志 2010-5-11 王玮 Add
                //AddLog("" + CurrentUserInfo.UserName + "设置了一个客源类别:客户姓名[" + customerDemandInfo.CustomerName + "]已设置了客源类别:[" + customerDemandInfo.Catalog + "]",
                //        OperationType.OperationTypeComboList()["OprType_SetCustomerType"].ToString());

                strRet = retExecResult(Constants.ExecResult.Succ, "类别设置成功", "");
            }
            return strRet;
        }
        catch (Exception ex)
        {
            strRet = retExecResult(Constants.ExecResult.Error, ex.Message, "");
            return strRet;
        }
    }

    //设定客需公开级别
    private string setDemandPubLevel(HttpContext context)
    {
        string strRet = string.Empty;
        Chenxin.Lib.House.Entity.Customer_DemandInfo entCustDemandInfo =
           (Chenxin.Lib.House.Entity.Customer_DemandInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Customer_DemandInfo));

        Chenxin.Lib.House.Entity.Customer_DemandInfo entUpdDemandInfo = Chenxin.Lib.House.BLL.Custom_Info.GetCustomerDemandInfoById(entCustDemandInfo.DemandId.ToString());

        if (entUpdDemandInfo == null)
        {
            strRet = retExecResult(Constants.ExecResult.Error, "数据已变更，请刷新后重新执行操作", "");
        }
        else
        {
            entUpdDemandInfo.PubLevel = entCustDemandInfo.PubLevel;

            Chenxin.Lib.House.Entity.House_TraceInfo entTraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
            entTraceInfo.TractorId = CurrentUserInfo.UserId;
            entTraceInfo.Tractor = CurrentUserInfo.UserName;
            entTraceInfo.Depart = CurrentUserInfo.DepartName;
            entTraceInfo.DepartId = CurrentUserInfo.DepartId;
            entTraceInfo.CityId = CurrentUserInfo.CityId;
            entTraceInfo.CityName = CurrentUserInfo.CityName;
            entTraceInfo.CompanyId = CurrentUserInfo.CompanyId;
            entTraceInfo.CompanyName = CurrentUserInfo.CompanyName;
            //添加客源信息
            string strTemp = Chenxin.Lib.House.BLL.Custom_Info.UpdateCustomDemandInfo(entUpdDemandInfo, entTraceInfo);
            
            //变更客户公开级别
            if (!entCustDemandInfo.CustomerId.Equals(Guid.Empty))
            {
                Chenxin.Lib.House.BLL.Customer_BaseInfo bllBaseInfo = new Chenxin.Lib.House.BLL.Customer_BaseInfo();
                Chenxin.Lib.House.Entity.Customer_BaseInfo entBaseInfo = bllBaseInfo.GetModel(entCustDemandInfo.CustomerId);

                entBaseInfo.PubLevel = entCustDemandInfo.PubLevel;

                Chenxin.Lib.House.Entity.House_TraceInfo entCTraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
                entCTraceInfo.TractorId = CurrentUserInfo.UserId;
                entCTraceInfo.Tractor = CurrentUserInfo.UserName;
                entCTraceInfo.Depart = CurrentUserInfo.DepartName;
                entCTraceInfo.DepartId = CurrentUserInfo.DepartId;
                entCTraceInfo.CityId = CurrentUserInfo.CityId;
                entCTraceInfo.CityName = CurrentUserInfo.CityName;
                entCTraceInfo.CompanyId = CurrentUserInfo.CompanyId;
                entCTraceInfo.CompanyName = CurrentUserInfo.CompanyName;
                //添加客源信息
                Chenxin.Lib.House.BLL.Custom_Info.UpdateCustomBaseInfo(entBaseInfo, entCTraceInfo);
                
                //bllBaseInfo.Update(entBaseInfo);
            }
            
            strRet = retExecResult(Constants.ExecResult.Succ, "公开级别设置成功", "");
        }
        return strRet;
    }
    
    //*******************************************
    //功能概要       ：响应字符串
    //参数説明       ：strMsg 消息 
    //返回值説明     ：void
    //功能詳細       ：权限检查
    //作成者         ：he.jifeng
    //作成日         ：2010-06-12
    //修改者         ：
    //修改日         ：
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        context.Response.ContentType = "text/plain";
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        string OP = context.Request.Params["op"];
        string clientModel = context.Request.Params["model"];
        bool bRet = false;

        try
        {
            if (string.IsNullOrEmpty(OP))
            {
                strMsg = retExecResult(Constants.ExecResult.Error, "参数有误", "");
                return false;
            }
            else
            {
                //传递参数用
                System.Collections.Hashtable per = new System.Collections.Hashtable();
                System.Collections.Hashtable confine = new System.Collections.Hashtable();
                Chenxin.Lib.House.Entity.Customer_DemandInfo entDemandInfo;
                Chenxin.Lib.House.Entity.Customer_BaseInfo entBaseInfo;
                OP = OP.ToLower();
                string strType = context.Request.Params["type"];

                switch (OP)
                {
                    case "checkpermit":
                        string code = context.Request.Params["code"];
                        switch (code)
                        {
                            case "setpublevel":
                                bRet = chkPubLevelSet(context, out strMsg);
                                break;
                            default:
                                bRet = true;
                                break;
                        }
                        break;
                    //状态
                    case "updstatus":
                        string DemandId = context.Request.Params["demandId"];
                        entDemandInfo = Chenxin.Lib.House.BLL.Custom_Info.GetCustomerDemandInfoById(DemandId);
                        //权限项
                        per.Add("ALL", Constants.Permit_EditCustomerDemand_All);
                        per.Add("CITY", Constants.Permit_EditCustomerDemand_City);
                        per.Add("COMPANY", Constants.Permit_EditCustomerDemand_Company);
                        per.Add("DEPART", Constants.Permit_EditCustomerDemand_Department);

                        //加入范围
                        confine.Add("CityId", entDemandInfo.CityId);
                        confine.Add("CompanyId", entDemandInfo.CompanyId);
                        confine.Add("OperatorId", entDemandInfo.OprPersonId);

                        //检查权限
                        if (CheckPermint(per, confine, chkDemandDepartPermit(entDemandInfo, "edit"), out strMsg))
                        {
                            bRet = chkDemandInfo(entDemandInfo);
                        }
                        else
                        {
                            bRet = false;
                        }

                        break;
                    case "edit":
                        //客户基本信息
                        if (strType.Equals("BaseInfo"))
                        {
                            //客户基本信息
                            string strBaseInfo = Regex.Replace(clientModel, @"DemandInfo_([\s\S])*?\042([\s\S])*?\042,", "", RegexOptions.None);
                            strBaseInfo = Regex.Replace(strBaseInfo, @"DemandInfo_([\s\S])*?\042([\s\S])*?\042\}", "}", RegexOptions.None);
                            strBaseInfo = strBaseInfo.Replace(",}", "}").Replace("CustomerInfo_", "");

                            //客源基本信息实体对象
                            Chenxin.Lib.House.Entity.Customer_BaseInfo entUpdBaseInfo =
                            (Chenxin.Lib.House.Entity.Customer_BaseInfo)JsonHelp.Convert2Entity(strBaseInfo, typeof(Chenxin.Lib.House.Entity.Customer_BaseInfo));

                            entBaseInfo = Chenxin.Lib.House.BLL.Custom_Info.GetCustomBaseInfo(entUpdBaseInfo.CustomerId.ToString());
                            if (entBaseInfo == null)
                            {
                                strMsg = retExecResult(Constants.ExecResult.Error, "客户信息丢失！", "");
                                return false;
                            }
                            //权限项
                            per.Add("ALL", Constants.Permit_EditCustomerInfo_All);
                            per.Add("CITY", Constants.Permit_EditCustomerInfo_City);
                            per.Add("COMPANY", Constants.Permit_EditCustomerInfo_Company);
                            per.Add("DEPART", Constants.Permit_EditCustomerInfo_Department);

                            //加入范围
                            confine.Add("CityId", entBaseInfo.CityId);
                            confine.Add("CompanyId", entBaseInfo.CompanyId);
                            confine.Add("OperatorId", entBaseInfo.OprPersonId);

                            //检查权限
                            if (CheckPermint(per, confine, chkBaseDepartPermit(entBaseInfo, "edit"), out strMsg))
                            {
                                bRet = chkBaseInfo(entBaseInfo);
                            }
                            else
                            {
                                bRet = false;
                            }
                        }
                        //客需信息
                        else if (strType.Equals("DemandInfo"))
                        {
                            //客户需求信息
                            string strDemandInfo = Regex.Replace(clientModel, @"CustomerInfo_([\s\S])*?\042([\s\S])*?\042,", "", RegexOptions.None);
                            strDemandInfo = Regex.Replace(strDemandInfo, @"CustomerInfo_([\s\S])*?\042([\s\S])*?\042\}", "}", RegexOptions.None);
                            strDemandInfo = strDemandInfo.Replace(",}", "}").Replace("DemandInfo_", "");

                            //客源需求信息实体对象
                            Chenxin.Lib.House.Entity.Customer_DemandInfo entUpdDemandInfo =
                            (Chenxin.Lib.House.Entity.Customer_DemandInfo)JsonHelp.Convert2Entity(strDemandInfo, typeof(Chenxin.Lib.House.Entity.Customer_DemandInfo));

                            entDemandInfo = Chenxin.Lib.House.DAL.Customer_DemandInfo.GetModel(entUpdDemandInfo.DemandId);
                            if (entDemandInfo==null)
                            {
                                strMsg = retExecResult(Constants.ExecResult.Error, "客需信息丢失！", "");
                                return false;
                             }
                            //权限项
                            per.Add("ALL", Constants.Permit_EditCustomerDemand_All);
                            per.Add("CITY", Constants.Permit_EditCustomerDemand_City);
                            per.Add("COMPANY", Constants.Permit_EditCustomerDemand_Company);
                            per.Add("DEPART", Constants.Permit_EditCustomerDemand_Department);

                            //加入范围
                            confine.Add("CityId", entDemandInfo.CityId);
                            confine.Add("CompanyId", entDemandInfo.CompanyId);
                            confine.Add("OperatorId", entDemandInfo.OprPersonId);

                            //检查层级权限
                            if (CheckPermint(per, confine, chkDemandDepartPermit(entDemandInfo, "edit"), out strMsg))
                            {
                                //检查公私权限
                                bRet = chkDemandInfo(entDemandInfo);
                            }
                            else
                            {
                                bRet = false;
                            }
                        }
                        break;
                    case "checkcustomerpopwind":
                        
                        entDemandInfo = (Chenxin.Lib.House.Entity.Customer_DemandInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Customer_DemandInfo));
                        entBaseInfo = Chenxin.Lib.House.BLL.Custom_Info.GetCustomBaseInfo(entDemandInfo.CustomerId.ToString());

                        //权限项
                        per.Add("ALL", Constants.Permit_EditCustomerInfo_All);
                        per.Add("CITY", Constants.Permit_EditCustomerInfo_City);
                        per.Add("COMPANY", Constants.Permit_EditCustomerInfo_Company);
                        per.Add("DEPART", Constants.Permit_EditCustomerInfo_Department);

                        //加入范围
                        confine.Add("CityId", entBaseInfo.CityId);
                        confine.Add("CompanyId", entBaseInfo.CompanyId);
                        confine.Add("OperatorId", entBaseInfo.OprPersonId);

                        //检查权限
                        if (CheckPermint(per, confine, chkBaseDepartPermit(entBaseInfo, "edit"), out strMsg))
                        {
                            bRet = chkBaseInfo(entBaseInfo);
                            if (bRet)
                            {
                                strMsg = "{success:1,msg:'',data:{permit:true}}";
                                context.Response.Write(strMsg);
                            }
                        }
                        else
                        {
                            bRet = false;
                        }
                        break;
                    case "checkcustomerdemendpopwind":
                        entDemandInfo = (Chenxin.Lib.House.Entity.Customer_DemandInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Customer_DemandInfo));

                        //权限项
                        per.Add("ALL", Constants.Permit_EditCustomerDemand_All);
                        per.Add("CITY", Constants.Permit_EditCustomerDemand_City);
                        per.Add("COMPANY", Constants.Permit_EditCustomerDemand_Company);
                        per.Add("DEPART", Constants.Permit_EditCustomerDemand_Department);

                        //加入范围
                        confine.Add("CityId", entDemandInfo.CityId);
                        confine.Add("CompanyId", entDemandInfo.CompanyId);
                        confine.Add("OperatorId", entDemandInfo.OprPersonId);

                        //检查层级权限
                        if (CheckPermint(per, confine, chkDemandDepartPermit(entDemandInfo, "edit"), out strMsg))
                        {
                            //检查公私权限
                            bRet = chkDemandInfo(entDemandInfo);
                            if (bRet)
                            {
                                strMsg = "{success:1,msg:'',data:{permit:true}}";
                                context.Response.Write(strMsg);
                            }
                        }
                        else
                        {
                            bRet = false;
                        }
                        break;
                    //其他
                    default:
                        bRet = true;
                        break;
                }
            }
            if (!bRet)
            {
                strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
            }
            else
            {
                strMsg = "{success:1,msg:'',data:{permit:true}}";
            }
            return bRet;
        }
        catch (Exception ex)
        {
            strMsg = string.Format("{success:1,msg:'{0}',data:{permit:false}}", ex.Message);
            return false;
        }
    }

    //公开级别设定权限
    private bool chkPubLevelSet(HttpContext context,out string strMsg)
    {

        System.Collections.Hashtable per = new System.Collections.Hashtable();
        System.Collections.Hashtable confine = new System.Collections.Hashtable();

        string DemandId = context.Request.Params["DemandId"];

        Chenxin.Lib.House.Entity.Customer_DemandInfo entDemandInfo = Chenxin.Lib.House.BLL.Custom_Info.GetCustomerDemandInfoById(DemandId);
        
        //权限项
        per.Add("ALL", Constants.Permit_SetPubLevel_All);
        per.Add("CITY", Constants.Permit_SetPubLevel_City);
        per.Add("COMPANY", Constants.Permit_SetPubLevel_Company);
        per.Add("DEPART", Constants.Permit_SetPubLevel_Department);

        //加入范围
        confine.Add("CityId", entDemandInfo.CityId);
        confine.Add("CompanyId", entDemandInfo.CompanyId);
        confine.Add("OperatorId", entDemandInfo.OprPersonId);

        return CheckPermint(per, confine, chkDemandDepartPermit(entDemandInfo, "setpublevel"), out strMsg);
    }
    
    //客需编辑权限检查
    private bool chkDemandInfo(Chenxin.Lib.House.Entity.Customer_DemandInfo entDemandInfo)
    {
        bool bRet = false;

        if (entDemandInfo.OprPersonId.Equals(CurrentUserInfo.UserId))
        {
            bRet = true;
        }
        else if (!CurrentUserInfo.ContainsPermit(Constants.Permit_EditCustomerDemand_Department))
        {
            //受保护客需(私客需)
            if (entDemandInfo.PubLevel == 0)
            {
                bRet = CurrentUserInfo.ContainsPermit(Constants.Permit_EditPrivDemand);
            }
            //公客需
            else
            {
                bRet = CurrentUserInfo.ContainsPermit(Constants.Permit_EditPubDemand);
            }
        }
        else
        {
            bRet = true;
        }       
        
        return bRet;
    }
    //客户基本信息编辑权限检查
    private bool chkBaseInfo(Chenxin.Lib.House.Entity.Customer_BaseInfo entBaseInfo)
    {
        bool bRet = false;

        if (entBaseInfo.OprPersonId.Equals(CurrentUserInfo.UserId))
        {
            bRet = true;
        }
        else if (!CurrentUserInfo.ContainsPermit(Constants.Permit_EditCustomerInfo_Department))
        {
            //受保护客户(私客)
            if (entBaseInfo.PubLevel == 0)
            {
                bRet = CurrentUserInfo.ContainsPermit(Constants.Permit_EditPrivCustomer);
            }
            //私客
            else
            {
                bRet = CurrentUserInfo.ContainsPermit(Constants.Permit_EditPubCustomer);
            }
        }
        else
        {
            bRet = true;
        }    
        return bRet;
    }

    //客户需求信息的部门权限检查
    private bool chkDemandDepartPermit(Chenxin.Lib.House.Entity.Customer_DemandInfo entDemandInfo, string op)
    {
        if (entDemandInfo.OprPersonId.Equals(CurrentUserInfo.UserId))
        {
            return true;
        }
        //检查有无权限
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" (Departid = '{0}' AND  Userid= '{1}') ", entDemandInfo.OprDepartId, CurrentUserInfo.UserId);
        System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation> list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetListArray(sb.ToString());
        if (list.Count > 0)
        {
            Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation struct_UserDepartRelation = list[0];
            switch (op)
            {
                case "edit":
                    //私客
                    if (entDemandInfo.PubLevel == 0)
                    {
                        return struct_UserDepartRelation.EditPrivDemand;
                    }
                    //公客
                    else
                    {
                        return struct_UserDepartRelation.EditPubDemand;
                    }
                    break;
                case "setpublevel":
                    return struct_UserDepartRelation.SetPubLevel;
                    break;
                default:
                    break;
            }
        }
        return false;
    }
    
    //客户基本信息的部门权限
    private bool chkBaseDepartPermit(Chenxin.Lib.House.Entity.Customer_BaseInfo entBaseInfo, string op)
    {
        if (entBaseInfo.OprPersonId.Equals(CurrentUserInfo.UserId))
        {
            return true;
        }
        //检查有无权限
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" (Departid = '{0}' AND  Userid= '{1}') ", entBaseInfo.OprDepartId, CurrentUserInfo.UserId);
        System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation> list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetListArray(sb.ToString());
        if (list.Count > 0)
        {
            Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation struct_UserDepartRelation = list[0];
            //私客
            if (entBaseInfo.PubLevel == 0)
            {
                return struct_UserDepartRelation.EditPrivCustomer;
            }
            //公客
            else
            {
                return struct_UserDepartRelation.EditPubCustomer;
            }
        }
        return false;
    }
    
    //获取需求
    private string getDemandByCustomerId(HttpContext context)
    {
        string strRet = string.Empty;
        StringBuilder strHtml = new StringBuilder();
        
        string CustomerId = context.Request.Params["CustomerId"];

        System.Collections.Generic.List<Chenxin.Lib.House.Entity.Customer_DemandInfo> lsDemand = Chenxin.Lib.House.BLL.Custom_Info.GetCustomerDemandInfo(CustomerId);

        if ( lsDemand!=null)
        {
            string strKind = string.Empty;
            string strType = string.Empty;
            string strHouseType = string.Empty;
            
            if (lsDemand[0].DemandKind == 10)
            {
                strKind = "求购";
            }
            else if (lsDemand[0].DemandKind == 20)
            {
                strKind = "求租";
            }
            else
            {
                strKind = "-";
            }

            if (lsDemand[0].DemandType == 10)
            {
                strType = "住宅";
            }
            else if (lsDemand[0].DemandType == 20)
            {
                strType = "商铺";
            }
            else if (lsDemand[0].DemandType == 30)
            {
                strType = "办公";
            }
            else
            {
                strType = "-";
            }

            if (lsDemand[0].DemandStyle_Room != null)
            {
                strHouseType = lsDemand[0].DemandStyle_Room.ToString() + "/";
            }
            else
            {
                strHouseType = "-/";
            }
            if (lsDemand[0].DemandStyle_Hall != null)
            {
                strHouseType = strHouseType + lsDemand[0].DemandStyle_Hall.ToString() + "/";
            }
            else
            {
                strHouseType = strHouseType + "-/";
            }
            if (lsDemand[0].DemandStyle_Toilet != null)
            {
                strHouseType = strHouseType + lsDemand[0].DemandStyle_Toilet.ToString() + "/";
            }
            else
            {
                strHouseType = strHouseType + "-/";
            }
            
            strHtml.Append("<table cellspacing=\"1\" class=\"tabsorternew\" style=\"width:100%;\">");
            strHtml.AppendFormat("<tr><td>客户姓名：{0}</td></tr>", lsDemand[0].CustomerName);
            strHtml.AppendFormat("<tr><td>需求种类：{0}</td></tr>", strKind);
            strHtml.AppendFormat("<tr><td>需求类型：{0}</td></tr>", strType);
            if (!string.IsNullOrEmpty(lsDemand[0].DemandZone))
            {
                strHtml.AppendFormat("<tr><td>需求区域：{0}</td></tr>", lsDemand[0].DemandZone);
            }
            if (!string.IsNullOrEmpty(lsDemand[0].DemandArea))
            {
                strHtml.AppendFormat("<tr><td>需求面积：{0}</td></tr>", lsDemand[0].DemandArea);
            }
            if (!string.IsNullOrEmpty(lsDemand[0].TotalPrice))
            {
                strHtml.AppendFormat("<tr><td>总(售/租)价：{0}</td></tr>", lsDemand[0].TotalPrice);
            }
            if (!string.IsNullOrEmpty(lsDemand[0].HouseBuyTime))
            {
                strHtml.AppendFormat("<tr><td>需求时间：{0}</td></tr>", lsDemand[0].HouseBuyTime);
            }
            if (!string.IsNullOrEmpty(lsDemand[0].HouseUse))
            {
                strHtml.AppendFormat("<tr><td>房屋用途：{0}</td></tr>", lsDemand[0].HouseUse);
            }
            if (!string.IsNullOrEmpty(lsDemand[0].Consider))
            {
                strHtml.AppendFormat("<tr><td>考虑因素：{0}</td></tr>", lsDemand[0].Consider);
            }
            if (!string.IsNullOrEmpty(lsDemand[0].ServiceDemand))
            {
                strHtml.AppendFormat("<tr><td>服务需求：{0}</td></tr>", lsDemand[0].ServiceDemand);
            }
            if (!string.IsNullOrEmpty(lsDemand[0].DemandBuilding))
            {
                strHtml.AppendFormat("<tr><td>物业类型：{0}</td></tr>", lsDemand[0].DemandBuilding);
            }
            if (!string.IsNullOrEmpty(lsDemand[0].SpecialDemand))
            {
                strHtml.AppendFormat("<tr><td>特殊需求：{0}</td></tr>", lsDemand[0].SpecialDemand);
            }

            strHtml.AppendFormat("<tr><td>房型需求：{0}</td></tr>", strHouseType);

            if (!string.IsNullOrEmpty(lsDemand[0].UnitPrice))
            {
                strHtml.AppendFormat("<tr><td>售单价：{0}</td></tr>", lsDemand[0].UnitPrice);
            }
            if (!string.IsNullOrEmpty(lsDemand[0].Fitment))
            {
                strHtml.AppendFormat("<tr><td>装修情况：{0}</td></tr>", lsDemand[0].Fitment);
            }
            if (!string.IsNullOrEmpty(lsDemand[0].ReturnRate))
            {
                strHtml.AppendFormat("<tr><td>期望回报率：{0}</td></tr>", lsDemand[0].ReturnRate);
            }
            
            strHtml.Append("</table>");
            //strHtml.Append("<ul>");
            //strHtml.Append("<li class=\"wid2 fl\">");
            //strHtml.AppendFormat("客户姓名：{0}",lsDemand[0].CustomerName);
            //strHtml.AppendFormat("需求种类：{0}", lsDemand[0].DemandKind);
            //strHtml.AppendFormat("需求类型：{0}", lsDemand[0].DemandType);
            //strHtml.Append("</li>");
            //strHtml.Append("</ul>");
            strRet = retExecResult(Constants.ExecResult.Succ, "", strHtml.ToString());
        }
        else
        {
            strRet = retExecResult(Constants.ExecResult.Error, "数据有误", "");
        }
        return strRet;
    }
}